package com.yc.encrypt;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class TestHash {




    public void m1() throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        String secret = "ca7e3bc1ada649beb96011040361e85a";
        String timestampStr = System.currentTimeMillis()+"";

        //注意：这里是有序的json按照put顺序
        JSONObject json = new JSONObject(new LinkedHashMap());

        json.put("reportCode", "123123123");
        json.put("phone", "11410000001");
        json.put("name", "丁应鑫");
        json.put("carType", "A");
        json.put("useCarDaySpan", "5");
        json.put("useCarTime", "2021-05-20 13:29:06");
        json.put("useCarCityCode", "330100");//（没有到达时间会传null）
        json.put("address", "西溪花园小区");
        json.put("longitude", "120.123123");
        json.put("latitude", "23.34344");
        json.put("drivingLicenceUrl", "https://img.chediandian.com/other/license/201806/1fc1f4d9-7d24-43e8-8a24-07814ad6a32b.jpg");
        json.put("drivingLicenceReverseUrl", "https://img.chediandian.com/other/license/201806/1fc1f4d9-7d24-43e8-8a24-07814ad6a32b.jpg");
        json.put("cardUrl", "http://img.chediandian.com/other/ent_boss_identity/201709/59c334f8e138232a33b8a796.jpg");
        json.put("cardReverseUrl", "https://img.chediandian.com/other/ent_boss_identity/201709/59c08943e13823ab55b8a78d.jpg");
        json.put("agreement", "https://img.chediandian.com/web/daibuche-cheshanshan/agreement/202105/1d6a4c85-c0c5-46be-850d-df32636a7baa.jpg");

        String body = json.toJSONString();
        //签名
        String signature = sign(secret,timestampStr + body);

        System.out.println(timestampStr);
        System.out.println(body);
        System.out.println(signature);
    }

    public void m2() throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        String secret = "ca7e3bc1ada649beb96011040361e85a";
        String timestampStr = System.currentTimeMillis()+"";

        //注意：这里是有序的json按照put顺序
        JSONObject json = new JSONObject(new LinkedHashMap());

        json.put("orderNo", "44");
        json.put("returnCarTime", "2021-05-25 12:12:12");
        json.put("returnCarCityCode", "330100");
        json.put("returnAddress", "西溪花园小区");
        json.put("returnlongitude", "120.22222");
        json.put("returnlatitude", "25.22222");
        json.put("customerPhone", "11400027718");
        String body = json.toJSONString();
        //签名
        String signature = sign(secret,timestampStr + json.toJSONString());

        System.out.println(timestampStr);
        System.out.println(body);
        System.out.println(signature);
    }

    public void m3() throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        String secret = "ca7e3bc1ada649beb96011040361e85a";
        String timestampStr = System.currentTimeMillis()+"";

        //注意：这里是有序的json按照put顺序
        JSONObject json = new JSONObject(new LinkedHashMap());

        json.put("orderNo", "44");
        String body = json.toJSONString();
        //签名
        String signature = sign(secret,timestampStr + json.toJSONString());

        System.out.println(timestampStr);
        System.out.println(body);
        System.out.println(signature);
    }

    //签名方法
    private static String sign(String secret, String stringToSign)
            throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        byte[] data = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(data);
    }



    public String signForMini(String header) {
        String apiKey = "8989DFB03174D268";
        String MINI_API_SIGN_KEY = "05b36da10a2f9f6a1e28436e43ecce2f";

        StringBuffer paramSb = new StringBuffer();
        TreeMap<String, String> paramsMap = JSONObject.parseObject(header, TreeMap.class);
        Iterator iter = paramsMap.entrySet().iterator();
        String entValue = "";
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            entValue = entry.getValue().toString();
            if (!"Sign".equalsIgnoreCase(entry.getKey().toString())) {
                paramSb.append(entry.getKey().toString() + entValue);
            }
        }
        String waitSignStr = (paramSb.toString() + apiKey);
        return cn.hutool.core.codec.Base64.encode(SecureUtil.hmacSha1(MINI_API_SIGN_KEY).digest(waitSignStr, CharsetUtil.UTF_8));
    }


    public void testSignForMini() {
        String headData = "{\"MobileBrand\":\"iPhone\",\"PlatType\":2,\"AreaId\":320114,\"Token\":\"5BD8EC47CB955A17B921198F18D8718D\",\"Timestamp\":1628144914862,\"AppSource\":\"Alipay\",\"CddUuId\":\"C203e3566b435b0ba4561ac6826a7e7c\",\"CddAppId\":20005,\"CityId\":3201,\"Version\":\"1.0.0.0\",\"Coordinate\":\"118.76890561057517,31.978502217389945\",\"SysVersion\":\"10.2.28.2000\",\"Sign\":\"PbVZ600xrkh0UR4woaW7YIX1rK4=\",\"MobileType\":\"iPhone10,2\",\"PlatVersion\":\"14.6\"}";
        JSONObject jo = JSONObject.parseObject(headData);
        jo.put("Timestamp", System.currentTimeMillis());
        String sign = signForMini(jo.toJSONString());
        jo.put("Sign", sign);
        System.out.println(jo.toJSONString());
    }

    public static void main(String[] args) throws Exception {
        TestHash th = new TestHash();
//        th.m1();
//        th.m2();
//        th.m3();
        th.testSignForMini();
    }


}
